package com.itheima.consumer.controller;

import com.itheima.consumer.domain.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {
    //注入DiscoveryClient
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private RestTemplate restTemplate;
    @GetMapping("/findGoodsById/{id}")
    public Goods findGoodsById(@PathVariable("id") int id){
        System.out.println("findGoodsById...."+id);
        /*
        * 定义Bean   restTemplate
        * 注入Bean
        * 调用方法
        * */
        //调用方法
        List<ServiceInstance> eurekaProvider = discoveryClient.getInstances("EUREKA_PROVIDER");
        //判断数据是否存在
        if (eurekaProvider != null && eurekaProvider.size() > 0){
            //在动态获取host与port
            ServiceInstance instance = eurekaProvider.get(0);
            String host = instance.getHost();//动态获取IP
            int port = instance.getPort();//动态获取端口
            //设置服务端的url地址(拼接host与port)
            String url = "http://"+host+":"+port+"/goods/findById/"+ id;
            Goods goods = restTemplate.getForObject(url, Goods.class);
            return goods;
        }
        return null;
    }
}
